import xml.etree.ElementTree as ET  
from xml.etree.ElementTree import SubElement
import os

def addContainer(parent:ET.Element,containerName:str,type:str,path:str):
    CONTAINER_VALUE = SubElement(parent,'ECUC-CONTAINER-VALUE')
    SubElement(CONTAINER_VALUE,'SHORT-NAME').text = containerName
    SubElement(CONTAINER_VALUE, 'DEFINITION-REF', attrib={'DEST': type}).text = path
    return CONTAINER_VALUE
            
    
def addParameter(PARAMETER_VALUES:ET.Element,type1,type3,para_path,para_valu):
    # type1
    # type2
    # type3

    PARAMETER_VALE = SubElement(PARAMETER_VALUES,type1)
    SubElement(PARAMETER_VALE, 'DEFINITION-REF', attrib={'DEST': type3}).text = para_path
    SubElement(PARAMETER_VALE,'VALUE').text = para_valu

def addReference(parent:ET.Element,type:str,selfPath:str,referPath:str):
    ECUC_REFERENCE_VALUE = SubElement(parent,'ECUC-REFERENCE-VALUE')
    SubElement(ECUC_REFERENCE_VALUE, 'DEFINITION-REF', attrib={'DEST': type}).text = selfPath
    SubElement(ECUC_REFERENCE_VALUE,'VALUE-REF', attrib={'DEST': 'ECUC-CONTAINER-VALUE'}).text = referPath

def addModule(parent:ET.Element,containerName:str,path:str):
    MODULE_CONFIGURATION_el = SubElement(parent,'ECUC-MODULE-CONFIGURATION-VALUES')
    SubElement(MODULE_CONFIGURATION_el,'SHORT-NAME').text = containerName
    SubElement(MODULE_CONFIGURATION_el, 'DEFINITION-REF', attrib={'DEST': 'ECUC-MODULE-DEF'}).text = path
    ModileCONTAINERS_el = SubElement(MODULE_CONFIGURATION_el,'CONTAINERS')
    return ModileCONTAINERS_el

class arxmlFile(object):
    def __init__(self) -> None:
        self.root = 'no define'

    def createArxmlFile(self):
        # self.root = ET.Element("AUTOSAR")
        self.root = ET.Element("AUTOSAR", {  
            "xmlns": "http://autosar.org/schema/r4.0",  
            "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",  
            "xsi:schemaLocation": "http://autosar.org/schema/r4.0 AUTOSAR_4-2-2.xsd"  
        }) 

    def createArxmlPackage(self,packagePath:str):
        if self.root == 'no define':
            self.createArxmlFile()

        pathList = packagePath.split('/')
        sourcePath = self.root
        for path in pathList:
            if path != '':
                sourcePath = SubElement(SubElement(sourcePath,'AR-PACKAGES'),'AR-PACKAGE')
                SubElement(sourcePath,'SHORT-NAME').text = path

        return SubElement(sourcePath,'ELEMENTS')

    def paraseArxmlFile(self,arxmlFileName):
        self.XmlFileName = arxmlFileName
        bufferXmlFile = arxmlFileName + '_Copy.arxml'

        file = open(arxmlFileName,"r",encoding='ISO-8859-1')
        file_write = open(bufferXmlFile,'w')

        while 1:
            line = file.readline()
            if not line:
                break
            if line.startswith('<AUTOSAR'):
                line = '<AUTOSAR>\n'
            file_write.write(line)
        file.close()
        file_write.close()

        self.root = ET.parse(bufferXmlFile).getroot() 
        self.root.attrib = {  
            "xmlns": "http://autosar.org/schema/r4.0",  
            "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",  
            "xsi:schemaLocation": "http://autosar.org/schema/r4.0 AUTOSAR_4-2-2.xsd"  
        }
        os.remove(bufferXmlFile)

    def findALLPackage(self,path,element,elementName):
        packageDict = dict()
        packagePath = path
        if elementName != '':
            packagePath += elementName + '/'
        elementName = ''
        for child in element:  
            if child.tag == 'SHORT-NAME' :
                elementName = child.text
            # AR-PACKAGE
            if child.tag == 'AR-PACKAGE' :
                package = child
                packageDict[packagePath] = package

            self.findALLPackage(packagePath,child,elementName)

        return packageDict
    
    def findPackageWithName(self,findName):
        self.findFlag = False
        self.findPackage = 'no define'
        self._findPackageWithName('/',self.root,'',findName)
        return self.findPackage
    
    def _findPackageWithName(self,path,element,elementName,findName):
        if self.findFlag == True:
            return
        
        packagePath = path
        if elementName != '':
            packagePath += elementName + '/'
        elementName = ''
        for child in element:  
            if child.tag == 'SHORT-NAME' :
                elementName = child.text
            # AR-PACKAGE
            if child.tag == 'AR-PACKAGE' :
                package = child

                packageName = 'no define'
                packageEl = 'no define'
                for child in package:  
                    if child.tag == 'SHORT-NAME' :
                        packageName = child.text
                    if child.tag == 'ELEMENTS':
                        packageEl = child
                #package is valid        
                if packagePath + packageName == findName and packageEl != 'no define':
                    self.findFlag = True
                    self.findPackage = packageEl
            self._findPackageWithName(packagePath,child,elementName,findName)
    
    def prettyXml(self,tree,indent,newline,level=0):
        treeList=list(tree)
        if len(treeList) > 0 and tree.text == None:
            tree.text=newline+indent*(level+1)

        for subElement in treeList:
            if treeList.index(subElement) < (len(treeList) - 1):
                subElement.tail=newline+indent*(level+1)
            else:
                subElement.tail=newline+indent*level
            
            self.prettyXml(subElement,indent,newline,level+1)



    def outputXml(self,outPath,OutFile):

        if not os.path.exists(outPath):  
            os.makedirs(outPath, exist_ok=True)  

        self.prettyXml(self.root,'  ','\n')
        self.tree = ET.ElementTree(self.root) 
        self.tree.write(outPath + OutFile, encoding="utf-8", xml_declaration=True)

